'usescript';

$(document).ready(function () {


    var config;
    //先去读取配置然后执行
    chrome.storage.local.get('config', function (item) {
        //拿到配置后再去执行
        config = item.config;
    });

    var button = '<button id="dfs_sync_button" class="dfs_button dfs_status">dfs168订单查询</button>';
    $(".trade-order-main").parent().find('div:first>div:last>div:first').prepend(button);

    //查询订单信息
    $(document).on('click','#dfs_sync_button',function () {
        if (!config || !config.query_order_api) {
            layer.open({title: '错误', content: '缺少接口地址的配置！', time: 2500});
            return false;
        }
        var flag = true;
        //遍历dom元素
        $(".trade-order-main").each(function () {
            var $this = $(this);
            var box = $this.find("table:first tbody:first tr:first td:first label:first");
            var order_sn = box.find("input:first").val();
            //如果拿到订单号
            if(order_sn)
            {
                var query_order = {'url': config.query_order_api, 'method': 'get', 'dataType': 'json', 'data': {'order_sn':order_sn}};
                //查询
                chrome.runtime.sendMessage(query_order, function (response) {
                    //成功响应
                    console.log(response);
                    if(response && response.code == 200)
                    {
                        $this.find('.dfs_staus').remove();

                        if(response.data.state == 1)
                        {
                            var order = response.data.data;

                            var shipping = order.is_shipping
                                ? '<span class="dfs_shipping_yes dfs_staus">dfs168已发货</span>'
                                :'<span class="dfs_shipping_no dfs_staus">dfs168未发货</span>';
                            box.append(shipping);

                            var submit = order.is_exists
                                ? '<span class="dfs_submit_yes dfs_staus">dfs168已采集</span>'
                                : '<span class="dfs_submit_no dfs_staus">dfs168未采集</span>';
                            box.append(submit);
                        }
                    }
                    if(response && response.code == 403 && flag == true){
                        flag = false;
                        alert('请确认接口已经登陆！');
                    }
                });
            }
        });
    });
});